package com.atxiaodei.kabudarpc.init;

import com.atxiaodei.kabudarpc.handler.ProcessHandler;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName SocketServerInitial
 * @Deacription TODO
 * @Author 卡布达
 * @Date 2021/10/31 15:24
 * @Version 1.0
 **/
//ApplicationListener<ContextRefreshedEvent> 容器刷新，就会触发的事件。也就是启动或者重启
@Component
public class SocketServerInitial implements ApplicationListener<ContextRefreshedEvent> {
    private final ExecutorService executorService=Executors.newCachedThreadPool();
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        ServerSocket serverSocket=null;

        try {
            serverSocket=new ServerSocket(8888);

            while (true){
                Socket socket = serverSocket.accept();

                executorService.execute(new ProcessHandler(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
